/**
 * This example takes a picture every 5s and print its size on serial monitor.
 */

// =============================== SETUP ======================================

// 1. Board setup (Uncomment):
// #define BOARD_WROVER_KIT
// #define BOARD_ESP32CAM_AITHINKER

/**
 * 2. Kconfig setup
 *
 * If you have a Kconfig file, copy the content from
 *  https://github.com/espressif/esp32-camera/blob/master/Kconfig into it.
 * In case you haven't, copy and paste this Kconfig file inside the src directory.
 * This Kconfig file has definitions that allows more control over the camera and
 * how it will be initialized.
 */

/**
 * 3. Enable PSRAM on sdkconfig:
 *
 * CONFIG_ESP32_SPIRAM_SUPPORT=y
 *
 * More info on
 * https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/kconfig.html#config-esp32-spiram-support
 */

// ================================ CODE ======================================

#include <esp_log.h>
#include <esp_system.h>
#include <nvs_flash.h>
#include <sys/param.h>
#include <string.h>

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

// support IDF 5.x
#ifndef portTICK_RATE_MS
#define portTICK_RATE_MS portTICK_PERIOD_MS
#endif

#include "esp_camera.h"
#include "driver/uart.h"
#include "uart2.h"

#define CAMERA_10M (10*1000*1000)

static const char *TAG = "app";

camera_config_t camera_config = {
    .ledc_channel = LEDC_CHANNEL_0,
    .ledc_timer = LEDC_TIMER_0,
    .pin_pwdn = -1,
    .pin_d0 = 33,
    .pin_d1 = 26,
    .pin_d2 = 27,
    .pin_d3 = 25,
    .pin_d4 = 32,
    .pin_d5 = 34,
    .pin_d6 = 39,
    .pin_d7 = 36,
    .pin_xclk = 0,
    .pin_pclk = 35,
    .pin_vsync = 21,
    .pin_href = 4,
    .pin_sscb_sda = 5,
    .pin_sscb_scl = 18,
    .pin_reset = 19,
    .xclk_freq_hz = CAMERA_10M,

    .pixel_format = PIXFORMAT_YUV422,//PIXFORMAT_JPEG,//PIXFORMAT_YUV422, //YUV422,GRAYSCALE,RGB565,JPEG
    .frame_size = FRAMESIZE_SXGA,    //QQVGA-UXGA Do not use sizes above QVGA when not JPEG

    .jpeg_quality = 35, //0-63 lower number means higher quality
    .fb_count = 1,       //if more than one, i2s runs in continuous mode. Use only with JPEG
    .grab_mode = CAMERA_GRAB_WHEN_EMPTY, //CAMERA_GRAB_WHEN_EMPTY,
    .fb_location = -1, /*!< The location where the frame buffer will be allocated */
};

static esp_err_t init_camera()
{
    //initialize the camera
    esp_err_t err = esp_camera_init(&camera_config);
    if (err != ESP_OK)
    {
        ESP_LOGE(TAG, "Camera Init Failed");
        return err;
    }

    return ESP_OK;
}
uint8_t flag = 0;
void app_main()
{
    initialise_uart();

    if(ESP_OK != init_camera()) {
        return;
    }

    // uint8_t **buf = NULL;
    // size_t len = 0;

    camera_fb_t * fb = NULL;
    esp_err_t res = ESP_OK;
    size_t _jpg_buf_len = 0;
    uint8_t * _jpg_buf = 0;

    while (1)
    {
        if (flag == 1) {
            flag = 0;

            fb = esp_camera_fb_get();
            esp_camera_fb_return(fb);
            fb = esp_camera_fb_get();
            esp_camera_fb_return(fb);

            if (!fb) {
                ESP_LOGE(TAG, "Camera capture failed");
                continue;
            }

            if(fb->format != PIXFORMAT_JPEG){
                bool jpeg_converted = frame2jpg(fb, 80, &_jpg_buf, &_jpg_buf_len);
                if(!jpeg_converted){
                    ESP_LOGE(TAG, "JPEG compression failed");
                    continue;
                }
            } else {
                _jpg_buf_len = fb->len;
                _jpg_buf = fb->buf;
            }

            ESP_LOGI(TAG, "size is %u", _jpg_buf_len);
            uart_write_bytes(UART_NUM_2, (const char*)_jpg_buf, _jpg_buf_len);
        }
        vTaskDelay(5000 / portTICK_RATE_MS);
    }
}

void Cmd_ReportImg(void *v, int a) {
    // uint8_t **buf = NULL;
    // size_t *len = NULL;

    // ESP_LOGI(TAG, "Taking picture...");
    // camera_fb_t *pic = esp_camera_fb_get();

    // // use pic->buf to access the image
    // ESP_LOGI(TAG, "size was: %zu bytes", pic->len);
    // frame2jpg(pic, 35, buf, len);
    // ESP_LOGI(TAG, "size was: %zu bytes", *len);
    // uart_write_bytes(UART_NUM_2, (const char*)(*buf), *len);

    if (flag == 0)   flag = 1;
}
